﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Fuse8.ContentManagementFramework.Domain;
using Fuse8.ContentManagementFramework.Domain.Commands;
using Fuse8.DomainFramework.Common.Locator;
using Fuse8.DomainFramework.DataAccess;
using Fuse8.DomainFramework.DataAccess.SqlDatabase;

namespace Fuse8.ContentManagementFramework.DataAccess.SqlAccess.Commands
{
    internal class CmsSiteSelectForHostnameDataCommand : CmsSiteSelectForHostnameCommand
    {
        public override CmsSite ExecuteOne()
        {
            IEnumerable<CmsSite> result = null;

            var factory = DependencyServiceLocator.Current.GetInstance<IUnitOfWorkFactory<CmsSite>>();

            var currentUnitOfWork = factory.Get(false) as SqlUnitOfWork<CmsSite>;

            if (currentUnitOfWork != null)
            {
                var mapper = DependencyServiceLocator.Current.GetInstance<ISqlEntityDataMapper<CmsSite, int>>();

                result = SqlUtility<CmsSite, int>.ExecuteReader(
                        currentUnitOfWork.Connection,
                        currentUnitOfWork.Transaction,
                        "cms_sp_SiteSelectForHostname",
                        new
                        {
                            Hostname = CommandParameter.Hostname
                        },
                        mapper);
            }

            return result != null ?
                result.FirstOrDefault() :
                null;
        }
    }
}
